<template>
  <div class="info-form">
    <Form
      ref="formValidate"
      :model="formValidate"
      :rules="ruleValidate"
      :label-width="80"
    >
      <FormItem label="用户名" prop="name">
        <i-input
          v-model="formValidate.name"
          clearable
          size="large"
          placeholder="请输入你的用户名"
        ></i-input>
      </FormItem>
      <FormItem label="密码" prop="password">
        <i-input
          type="password"
          v-model="formValidate.password"
          clearable
          size="large"
          placeholder="请输入你的密码"
        ></i-input>
      </FormItem>
      <FormItem label="确认密码" prop="repassword">
        <i-input
          type="password"
          v-model="formValidate.repassword"
          clearable
          size="large"
          placeholder="请再次输入你的密码"
        ></i-input>
      </FormItem>
      <Button
        type="error"
        size="large"
        long
        @click="handleSubmit('formValidate')"
        >注册</Button
      >
    </Form>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import { signUp } from '~/api/user.js'
export default {
  name: 'InputInfo',
  data() {
    const validatePassCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.formValidate.password) {
        callback(new Error('两次输入的密码不一样'))
      } else {
        callback()
      }
    }
    return {
      formValidate: {
        name: '',
        password: '',
        repassword: ''
      },
      ruleValidate: {
        name: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { type: 'string', min: 6, message: '密码长度不能小于6', trigger: 'blur' }
        ],
        repassword: [
          { validator: validatePassCheck, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    ...mapMutations('user', ['SET_SIGN_UP_SETP']),
    handleSubmit(name) {
      const father = this
      // eslint-disable-next-line space-before-function-paren
      this.$refs[name].validate(async (valid) => {
        if (valid) {
          const password = await father.$encrypt(father.formValidate.password)
          // 验证通过，发出注册请求
          signUp({
            username: this.formValidate.name,
            password,
            phone: this.$route.query.phone
          }).then(res => {
            if (res.code === 200) {
              this.$Message.success('注册成功')
              // 步骤更新为最后一步
              father.SET_SIGN_UP_SETP(2)
              this.$router.push({ path: '/signUp/signUpDone' })
            } else {
              this.$Message.error('用户名已存在，请换一个')
            }
          })
        } else {
          this.$Message.error('请检查填写信息')
        }
      })
    }
  }
}
</script>

<style scoped>
.info-form {
  width: 90% !important;
}
</style>
